package com.feituan.core.persistence.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feituan.core.persistence.mapper.IntegrationRecordMapper;
import com.feituan.core.persistence.service.IIntegrationProductService;
import com.feituan.core.persistence.service.IIntegrationRecordService;
import com.feituan.core.persistence.service.IUserService;
import com.feituan.core.pojo.entity.IntegrationProduct;
import com.feituan.core.pojo.entity.IntegrationRecord;
import com.feituan.core.pojo.entity.User;
import com.feituan.core.pojo.request.IntegrationRecordReq;
import com.feituan.core.pojo.response.IntegrationRecordRes;
import com.feituan.core.pojo.response.page.PageData;
import com.feituan.core.util.OrderNumberGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class IntegrationRecordServiceImpl extends ServiceImpl<IntegrationRecordMapper, IntegrationRecord>  implements IIntegrationRecordService {


    @Resource
    private IUserService userService;

    @Resource
    private IIntegrationProductService iIntegrationProductService;
    /**
     * 新增积分使用记录
     * @param recordReq recordReq
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveRecord(IntegrationRecordReq recordReq) {
        // 用户积分
        User userSource = userService.selectById(recordReq.getUserId());
        Integer integration = userSource.getIntegration();
        if (integration == null && integration == 0) {
            return "false";
        }
        if (integration < recordReq.getIntegration()) {
            return "false";
        }
        int newIntegration = integration - recordReq.getIntegration();

        //
        IntegrationRecord integrationRecord = new IntegrationRecord();
        BeanUtils.copyProperties(recordReq, integrationRecord);
        // 自动生成订单号
        integrationRecord.setNumber(OrderNumberGenerator.generateOrderNumber());
        integrationRecord.setCreateTime(new Date());
        integrationRecord.setStatus(1);
        int res = this.getBaseMapper().insert(integrationRecord);
        // 扣减用户积分
        User user = new User();
        user.setId(recordReq.getUserId());
        user.setIntegration(newIntegration);
        int i = userService.updateIntegration(user);
        return integrationRecord.getNumber();
    }

    /**
     * 订单发货
     * @param recordReq recordReq
     * @return
     */
    @Override
    public int sendOrder(IntegrationRecordReq recordReq) {
        IntegrationRecord integrationRecord = new IntegrationRecord();
        BeanUtils.copyProperties(recordReq, integrationRecord);
        integrationRecord.setStatus(2);
        integrationRecord.setSendTime(new Date());
        return this.getBaseMapper().updateById(integrationRecord);
    }

    /**
     * 列表查询
     * @param recordReq recordReq
     * @return
     */
    @Override
    public PageData<IntegrationRecordRes> selectList(IntegrationRecordReq recordReq) {
        Page<IntegrationRecord> page = new Page<>();
        page.setCurrent(recordReq.getPage());
        page.setSize(recordReq.getLimit());
        LambdaQueryWrapper<IntegrationRecord> qw = new LambdaQueryWrapper<>();
        qw.like(!StringUtils.isEmpty(recordReq.getNumber()), IntegrationRecord::getNumber, recordReq.getNumber());
        qw.eq(recordReq.getStatus() != null, IntegrationRecord::getStatus, recordReq.getStatus());
        qw.eq(recordReq.getUserId() != null, IntegrationRecord::getUserId, recordReq.getUserId());
        // todo 查询条件
        Page<IntegrationRecord> integrationRecordPage = this.baseMapper.selectPage(page, qw);
        if (CollectionUtils.isEmpty(integrationRecordPage.getRecords())) {
            return PageData.build(1, 0, null);
        }
        List<IntegrationRecordRes> integrationRecordResList = new ArrayList<>();
        integrationRecordPage.getRecords().forEach(el -> {
            fillInfo(integrationRecordResList, el);
        });
        return PageData.build(integrationRecordPage.getCurrent(), integrationRecordPage.getTotal(), integrationRecordResList);
    }

    private void fillInfo(List<IntegrationRecordRes> integrationRecordResList, IntegrationRecord el) {
        IntegrationRecordRes integrationRecordRes = new IntegrationRecordRes();
        BeanUtils.copyProperties(el, integrationRecordRes);
        integrationRecordRes.setUser(userService.selectById(el.getUserId()));
        integrationRecordRes.setIntegrationProductRes(iIntegrationProductService.selectById(el.getProductId()));
        integrationRecordResList.add(integrationRecordRes);
    }

    /**
     * 用户id查询订单
     * @param userId 用户id
     * @return
     */
    @Override
    public List<IntegrationRecordRes> selectListByUserId(Long userId) {
        LambdaQueryWrapper<IntegrationRecord> qw = new LambdaQueryWrapper<>();
        // todo 查询条件
        qw.eq(true, IntegrationRecord::getUserId, userId);
        List<IntegrationRecord> integrationRecords = this.baseMapper.selectList(qw);
        if (CollectionUtils.isEmpty(integrationRecords)) {
            return null;
        }
        List<IntegrationRecordRes> integrationRecordResList = new ArrayList<>();
        integrationRecords.forEach(el -> {
            fillInfo(integrationRecordResList, el);
        });

        return integrationRecordResList;
    }

    /**
     * 修改兑换记录
     * @param recordReq recordReq
     * @return
     */
    @Override
    public int updateRecord(IntegrationRecordReq recordReq) {
        // todo 待确定字段
        return 0;
    }

    @Override
    public IntegrationRecordRes selectByNumber(String number) {
        LambdaQueryWrapper<IntegrationRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(true, IntegrationRecord::getNumber, number);
        IntegrationRecord integrationRecord = this.getBaseMapper().selectOne(qw);

        IntegrationRecordRes integrationRecordRes = new IntegrationRecordRes();
        BeanUtils.copyProperties(integrationRecord, integrationRecordRes);
        integrationRecordRes.setUser(userService.selectById(integrationRecord.getUserId()));
        integrationRecordRes.setIntegrationProductRes(iIntegrationProductService.selectById(integrationRecord.getProductId()));
        return integrationRecordRes;
    }
}
